package com.mediacloud.app.newsmodule.activity;


import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import com.chinamcloud.collect.AcquisitionManager;
import com.mediacloud.app.appfactory.cache.AppConfig;
import com.mediacloud.app.assembly.views.ImageButtonX;
import com.mediacloud.app.assembly.views.NetImageViewE;
import android.widget.TextView;
import com.mediacloud.app.cloud.ijkplayersdk.music.MusicPlayer.PlayCode;
import com.mediacloud.app.cloud.ijkplayersdk.untils.Tools;
import com.mediacloud.app.model.activity.BaseBackActivity;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.broadcast.AudioBackgroundBroad;
import com.mediacloud.app.newsmodule.broadcast.AudioVodBroadcast;
import com.mediacloud.app.newsmodule.fragment.album.AlbumFragment;
import com.mediacloud.app.newsmodule.interfaces.AlbumClickCall;
import com.mediacloud.app.newsmodule.service.AudioConst;
import com.mediacloud.app.newsmodule.service.AudioLivePlayService;
import com.mediacloud.app.newsmodule.service.AudioVodPlayService;
import com.mediacloud.app.newsmodule.service.servicenotification.MediaNotificationManager;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.user.utils.DeviceInfo;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.shared.AppSharePreference;
import com.tencent.mmkv.MMKV;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yoake on 2016/12/27.
 */

public class AlbumAudioActivity extends BaseBackActivity implements DataInvokeCallBack<ArticleItemReciver>, AudioVodBroadcast.AudioVodBroad {
    private PlayCode VodPlayMode = PlayCode.ORDER_PLAY;
    private final String PlayMode = "PlayMode";
    protected ArticleItem articleItem;
    protected CatalogItem catalogItem;
    protected CatalogItem navigate;
    protected AlbumFragment fragment;
    public AlbumClickCall call;
    protected NewsDetailInvoker newsDetailInvoker;
    protected AudioVodBroadcast broadcast;
    protected Map<String, String> lines = new HashMap<String, String>();
    protected NetImageViewE albumAudio;
    protected ImageButtonX playBtn;
    protected boolean isPlaying = false;
    protected boolean isComplete = true;
    protected boolean getDeatils = false;
    protected SeekBar Aseekbar;
    protected boolean isFromBackPlay = false;
    protected TextView currentPlayPosition;
    protected TextView totoalLength;
    protected boolean isAutoPlay = true;
    protected ImageButtonX back;
    String cdnEncrypt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        KillMusicUtils.stopAPS(this);
        Map<String, ? extends Object> value = AppSharePreference.getSharedData(PlayMode, this);
        if (value != null && value.containsKey(PlayMode)) {
            int modeValue = Integer.valueOf("" + value.get(PlayMode));
            if (modeValue == AudioConst.SingleLoop)
                VodPlayMode = PlayCode.SINGLE_LOOP_PLAY;
            else
                VodPlayMode = PlayCode.ORDER_PLAY;
        }
        initBroad();
        initBaseViews();
        showPageTransition();
    }

    @Override
    public int getLayoutResID() {
        return R.layout.activity_album_audio;
    }


    protected void initBaseViews() {
        navigate = getIntent().getParcelableExtra("catalog");
        catalogItem = getIntent().getParcelableExtra("data");
        newsDetailInvoker = new NewsDetailInvoker(this);
        currentPlayPosition = findViewById(R.id.currentPlayPosition);
        totoalLength = findViewById(R.id.totoalLength);
        albumAudio = findViewById(R.id.albumAudio);
        Aseekbar = findViewById(R.id.Aseekbar);
        setSeekBarListener();
        float num = 16.0f / 6.0f;
        ViewGroup.LayoutParams layoutParams = albumAudio.getLayoutParams();
        layoutParams.height = (int) (getResources().getDisplayMetrics().widthPixels / num);
        albumAudio.setLayoutParams(layoutParams);
        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        /**
         * Fragment 回调
         */
        call = new AlbumClickCall() {
            @Override
            public void clickItem(Parcelable p) {
                articleItem = (ArticleItem) p;
                if (isFromBackPlay) {
                    isFromBackPlay = false;
                    isPlaying = true;
                    getDeatils = true;
                    isComplete = false;
                    if(articleItem!=null&&AppConfig.albumItemId==articleItem.getId())
                    {
                        updateToggleDrawable();
                    }
                    return;
                }
                isPlaying = false;
                isComplete = true;
                getDeatils = false;
                updateToggleDrawable();
                if (articleItem != null) readStatus();
                stopPlay();
                playBtn.setClickable(false);
                currentPlayPosition.setText(getResources().getString(R.string.albumAudioTime));
                totoalLength.setText(getResources().getString(R.string.albumAudioTime));
                Aseekbar.setProgress(0);
                mRootView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getAudioDetail();
                    }
                }, 500);
            }
        };
        playBtn = findViewById(R.id.albumAudioPlayBtn);
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleAudio();
            }
        });
        if (AppConfig.albumCatalogId.equals(catalogItem.getCatid())) {
            isFromBackPlay = true;
        } else {
            stopPlay();
            AppConfig.albumItemId = -1;
            AppConfig.albumCatalogId = "";
            sendHideFloaWinMsg();
        }

        back = findViewById(R.id.albumaduio_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        /**
         * 初始化Fragment
         */
        fragment = new AlbumFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id", catalogItem.getCatid());
        bundle.putString("title", catalogItem.getCatname());
        bundle.putLong("lastItemid", AppConfig.albumItemId);
        fragment.setArguments(bundle);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.listContentInfo_audio, fragment);
        transaction.show(fragment);
        transaction.commitNowAllowingStateLoss();
    }

    protected void getAudioDetail()
    {
        if(articleItem==null)
            return;
        String navigate_id = navigate != null ? navigate.getCatid() : "";

        newsDetailInvoker.getArticleById("" + articleItem.getId(),  navigate_id);
    }

    @Override
    public void success(ArticleItemReciver data)
    {
        if (data.state) {
            if (data.articleItem != null && fragment != null) {
                fragment.item = articleItem;
            }
            try {
                JSONObject objectAll = new JSONObject(data.articleItem.getAudio());
                cdnEncrypt = objectAll.optString("cdnConfigEncrypt");
                JSONArray pcArray = objectAll.optJSONArray("PC");
                for (int i = 0; i < pcArray.length(); i++) {
                    JSONObject object = pcArray.optJSONObject(i);
                    lines.put(object.optString("title"), object.optString("url"));
                }
                totoalLength.setText(data.articleItem.getProp4());
                playBtn.setClickable(true);
                getDeatils = true;
                if (isAutoPlay) {
                    toggleAudio();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void fault(Object data) {
    }

    protected void initBroad() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(AudioVodBroadcast.Audio_UpdateTime);
        filter.addAction(AudioVodBroadcast.AudioComplete);
        broadcast = new AudioVodBroadcast();
        registerReceiver(broadcast, filter);
        broadcast.audioLiveBroadHanlder = this;

        Intent intent = new Intent();
        intent.putExtra(AudioConst.Action, AudioConst.CREATE_ACTIVITY);
        intent.setClass(this, AudioVodPlayService.class);
        startService(intent);
    }

    @Override
    public void updateCurrentTime(Intent intent) {
        Aseekbar.setEnabled(true);
        long time = intent.getLongExtra("time", 0);
        long total = intent.getLongExtra("total", 0);
        int cur = (int) (time / 1000);
        int tot = (int) (total / 1000);
        String currentTime = Tools.convertTimeFormat(cur);
        String duration = Tools.convertTimeFormat(tot);
        currentPlayPosition.setText(currentTime);
        totoalLength.setText(duration);
        Aseekbar.setMax(tot);
        Aseekbar.setProgress(cur);
        if (!isPlaying) {
            isPlaying = true;
            updateToggleDrawable();
        }
    }

    @Override
    public void audioComplete(Intent intent) {
        isPlaying = false;
        isComplete = true;
        updateToggleDrawable();
    }

    @Override
    public void seekComplete() {

    }

    @Override
    public void togglePauseAudio(Intent intent) {

    }

    protected void startPlay() {
        Intent intent = new Intent();
        intent.putExtra(AudioConst.Action, AudioConst.PlayVod);
        intent.putExtra("cdnEncrypt",cdnEncrypt);
        intent.putExtra("cdn_iv", AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
        intent.putExtra("cdn_key",AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);
        if(lines.values().size()>0)
        {
            intent.putExtra("url",lines.values().toArray()[0].toString());
        }
//        intent.putExtra("url", lines.get(getResources().getString(R.string.standard_audio)));
//        intent.putExtra("url", "http://mp3.haoduoge.com/s/2016-12-28/1482857534.mp3");
        intent.putExtra("data", articleItem);
        intent.putExtra("catalog", catalogItem);
        intent.putExtra("audioType", MediaNotificationManager.TYPE_IMAGE_TEXT);
        intent.putExtra("navigate",navigate);
        intent.setClass(this, AudioVodPlayService.class);
        startService(intent);
    }



    protected void stopPlay() {
        Intent intent = new Intent();
        intent.putExtra(AudioConst.Action, AudioConst.ChangeLine);
        intent.setClass(this, AudioVodPlayService.class);
        startService(intent);
    }

    protected void updateToggleDrawable() {
        Drawable toggleDrawable;
        if (isPlaying) {
            toggleDrawable = getResources().getDrawable(R.drawable.audio_pausbtn);
        } else {
            toggleDrawable = getResources().getDrawable(R.drawable.audio_playbtn);
        }
        playBtn.setBackground(toggleDrawable);
    }


    void toggleAudio() {
        Intent intent = new Intent();
        intent.setClass(this, AudioVodPlayService.class);
        if (isPlaying) {
            isPlaying = false;
            intent.putExtra(AudioConst.Action, AudioConst.Pause);
            startService(intent);
        } else {

            if (!isComplete) {
                intent.putExtra(AudioConst.Action, AudioConst.OnResume);
                startService(intent);
            } else {
                isComplete = false;
                startPlay();
            }
        }
        updateToggleDrawable();
    }


    protected final void sendShowFloaWinMsg() {
        Intent intent = new Intent();
        intent.setAction(AudioBackgroundBroad.ShowAction);
        intent.putExtra("data", articleItem);
        intent.putExtra("catalog", catalogItem);
        intent.putExtra("isAlbum", true);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    protected final void sendHideFloaWinMsg() {
        Intent intent = new Intent();
        intent.setAction(AudioBackgroundBroad.HideAction);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    @Override
    public void finish() {
//        Map<String, ? extends Object> value = AppSharePreference.getSharedData(TAG, this);
//        boolean needShow = value != null && value.containsKey(TAG) && isPlaying;
        if(readStatusInvoker!=null)
            readStatusInvoker.destory();
        readStatusInvoker=null;
        boolean isPad = DeviceInfo.getDeviceInfo(this).isPad();
        MMKV.defaultMMKV().encode("Audio_ID",-1L);
        sendHideFloaWinMsg();
        //没有播放  释放播放器
        if ((!isPlaying && getDeatils) || isPad) {
            KillMusicUtils.stopAPS(this);
            AppSharePreference.clearShareData(TAG, this);
            AppSharePreference.clearShareData(PlayMode, this);
            AppConfig.albumItemId = -1;
            AppConfig.albumCatalogId = "";
        }
        //正在播放  发个广播  显示那个啥子j8浮窗
        else if (isPlaying) {
            mRootView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendShowFloaWinMsg();
                }
            }, 500);
            if (articleItem != null) {
                MMKV.defaultMMKV().encode("Audio_ID",articleItem.getId());

                AppConfig.albumItemId = articleItem.getId();
                AppConfig.albumCatalogId = catalogItem.getCatid();
            }
        }

        KillMusicUtils.audioVodAction(this, AudioConst.StopUpdateTime);
        super.finish();
        if (newsDetailInvoker != null) {
            newsDetailInvoker.destory();
            newsDetailInvoker = null;
        }
        if (newsDetailInvoker != null) {
            newsDetailInvoker.destory();
            newsDetailInvoker = null;
        }
        if (broadcast != null){
            unregisterReceiver(broadcast);
            KillMusicUtils.audioVodAction(this, AudioConst.DESTROY_ACTIVITY);
        }

    }

    boolean isSeekAction = false;

    protected void setSeekBarListener() {
        SeekBar.OnSeekBarChangeListener seekListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                if (isSeekAction) {
                    Log.v(TAG, "progress: " + progress);

                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekAction = true;
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int iseekPos = seekBar.getProgress();
                seek(iseekPos);
                Log.v(TAG, "seek to " + iseekPos);
            }
        };
        Aseekbar.setOnSeekBarChangeListener(seekListener);
    }

    protected void seek(int postion) {
        if (!isComplete) {
            Intent intent = new Intent();
            intent.putExtra(AudioConst.Action, AudioConst.DirectSeek);
            intent.setClass(this, AudioVodPlayService.class);
            intent.putExtra("time", postion * 1000L);
            startService(intent);
        }
    }

    ReadStatusInvoker readStatusInvoker;
    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(),articleItem,data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(),articleItem,AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }

    @Override
    protected void onStart() {
        super.onStart();
        UserInfo info = UserInfo.getUserInfo(this);
        if(articleItem != null){
            AcquisitionManager.getInstance().readEnter(info,""+articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()),articleItem.getUrl(),articleItem.getTitle(),articleItem.getContent());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        UserInfo info = UserInfo.getUserInfo(this);
        if(articleItem != null){
            AcquisitionManager.getInstance().readExit(info,""+articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()),articleItem.getUrl(),articleItem.getTitle(),articleItem.getContent());
        }
    }
}